<template>
  <el-dialog width="500px" :title="dialogTitle" v-model="dialogFormVisible" :draggable="true" @close="dialogClose">
    <el-form v-loading="loading" ref="dialogFormRef" :model="dialogForm" :rules="dialogFormRules">
      <el-form-item prop="headImg" label="Banner图">
        <img v-show="!dialogForm.headImg" style="width:100px;cursor:pointer" src="@a/imgs/img-icon.png" alt="" @click="uploadImg">
        <div class="upload-box" v-show="dialogForm.headImg">
          <img :src="dialogForm.headImg" alt="">
          <el-icon v-show="!isEdit" color="#ffffff" class="upload-close" @click="removeImg">
            <Close />
          </el-icon>
        </div>
        <div style="font-size: 12px;color: #707070;margin-left: 10px;">建议上传16：9的jpg/png</div>
        <input ref="uploadInputRef" style="display:none" type="file" accept="image/*" @change="uploadChange">
      </el-form-item>
      <!-- <el-form-item prop="linkUrl" label="跳转地址">
        <el-input v-model="dialogForm.linkUrl" placeholder="点击banner跳转到..." @keypress.enter="submitHandle" />
      </el-form-item> -->
      <el-form-item prop="power" label="展现权重">
        <el-input v-model="dialogForm.power" type="number" placeholder="banner由权重高到低轮播" @keypress.enter="submitHandle" />
      </el-form-item>
      <el-form-item prop="type" label="Banner类别">
        <el-select :disabled="isEdit" v-model="dialogForm.type" placeholder="请选择Banner类别" filterable>
          <el-option v-for="item in bannerType" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer" v-show="!loading">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitHandle">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { computed, reactive, ref, toRefs } from 'vue'
import { getStore, successDeal, warningDeal } from '@/utils/utils'
import api from '../api'
import axios from "axios"
import { useStateStore } from '@/store'
export default {
  setup(props, context) {
    const store = useStateStore()

    const dialogFormRef = ref(null)
    const uploadInputRef = ref(null)

    const headImgPass = (rule, value, callback) => {
      if (!state.dialogForm.headImg) {
        callback(new Error('请上传Banner图片'))
      } else {
        callback()
      }
    }

    const state = reactive({
      loading: false,
      isEdit: false,
      dialogFormVisible: false,

      dialogForm: {},
      dialogFormRules: {
        headImg: [
          { required: true, validator: headImgPass, trigger: 'blur' },
        ],
        power: [
          { required: true, message: '请输入展现权重', trigger: 'blur' },
        ],
        type: [
          { required: true, message: '请选择Banner类别', trigger: 'blur' },
        ],
      },

      dialogTitle: computed(() => {
        return state.isEdit ? '编辑Banner' : '新增Banner'
      }),

      bannerType: computed(() => {
        return store.getBannerType
      })
    })

    function dialogShow(isEdit = false, data = {}) {
      state.isEdit = isEdit
      state.dialogForm = { ...data } || {}
      state.dialogFormVisible = true
    }

    function dialogClose() {
      dialogFormRef.value && dialogFormRef.value.resetFields()
    }

    function submitHandle() {
      dialogFormRef.value.validate((valid, fields) => {
        if (valid) {
          const obj = {
            ...state.dialogForm
          }
          const apiName = state.isEdit ? 'bannerModify' : 'bannerAdd'
          api[apiName](obj).then(res => {
            if (res.code == '200') {
              successDeal(res.msg)
              context.emit('dialogClose')
              state.dialogFormVisible = false
            } else {
              warningDeal(res.msg)
            }
          }).catch(err => {
            console.log(err)
          })
        }
      })
    }

    function uploadImg() {
      uploadInputRef.value.click()
    }

    async function uploadFile(fileForm) {
      if (state.loading) return
      state.loading = true
      let path = null
      let param = new FormData()  // 创建form对象
      param.append('file', fileForm.file, fileForm.fileName)  // 通过append向form对象添加数据
      const token = window.localStorage.getItem("USER_TOKEN_INRE") || '';
      const uesrInfo = getStore("USER_INFO_INRE") || {};
      const Authorization = getStore("USER_AUTHOR_INRE") || {
        Authorization: `'','','',3,20,''`,
      };
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          token: token ? `Bearer ${token}` : '',
          username: uesrInfo.username || '',
          Authorization: Authorization.Authorization,
          platformHeadType: 'rcmsPlatform',
        }
      }
      let url = '/ums/file/upload/user/pub'
      await axios.post(url, param, config).then(res => {
        if (res.data.code == '200') {
          path = res.data.data.ossUrl
        } else {
          warningDeal(res.data.msg)
        }
      }).catch(err => {
        console.log(err)
      })
      state.loading = false
      state.dialogForm.headImg = path
    }

    //上传文件
    async function uploadChange(e) {
      const fileTypeList = ['jpg', 'jpeg', 'png', 'gif']
      let fileType = e.target.files[0].name.replace(/.+\./, "")
      if (!fileTypeList.includes(fileType)) {
        warningDeal(`请上传${fileTypeList.join(',')}文件`)
        return false
      }
      const fileForm = {}
      fileForm.file = e.target.files[0]
      fileForm.fileName = e.target.files[0].name
      await uploadFile(fileForm)
      uploadInputRef.value.value = ''
    }

    function removeImg() {
      state.dialogForm.headImg = null
    }

    return {
      ...toRefs(state),
      dialogFormRef,
      uploadInputRef,
      dialogShow,
      dialogClose,
      submitHandle,
      uploadImg,
      uploadChange,
      removeImg,
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-box {
  position: relative;
  > img {
    max-width: 200px;
  }
  .upload-close {
    position: absolute;
    right: 0;
    top: 0;
    cursor: pointer;
    background-color: rgba($color: #000000, $alpha: 0.5);
  }
}
</style>